package com.bdqn.appjob.shiro;

import com.bdqn.appjob.entity.DevUser;
import com.bdqn.appjob.service.dev.DevUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

public class DevRealm extends AuthorizingRealm {

    @Autowired
    private DevUserService devUserService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权==>>>doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        DevUser currentDevUser = (DevUser) subject.getPrincipal();       //拿到devUser对象

        //设置当前用户的权限
        info.addStringPermission(currentDevUser.getPerms());

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证==>>>doGetAuthenticationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken)token;

        //连接用户名,密码
        DevUser devUser = devUserService.selectLogin(userToken.getUsername());

        if(devUser == null){        //没有这个用户
            return null;        //UnknownAccountException
        }
        //密码认证,shiro来做  加密了
        return new SimpleAuthenticationInfo(devUser,devUser.getDevPassword(),"");
    }
}
